
package com.jf.cloud.user.controller.app;

import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.rocketmq.config.RocketMqConstant;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.user.model.UserBalanceLog;
import com.jf.cloud.user.model.UserExtension;
import com.jf.cloud.user.service.UserBalanceLogService;
import com.jf.cloud.user.service.UserExtensionService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @author zz
 * @date 2021/5/11
 */
@RestController
@RequestMapping("/user_balance")
@Tag(name = "app-余额支付")
public class UserBalancePayController {

    @Autowired
    private UserExtensionService userExtensionService;

    @Autowired
    private RocketMQTemplate balancePayTemplate;

    @Autowired
    private UserBalanceLogService userBalanceLogService;

    @PostMapping("/balance_pay")
    @Operation(summary = "支付" , description = "余额支付")
    public ServerResponseEntity<Void> pay(@RequestBody Long payId) {
        Long userId = AuthUserContext.get().getUserId();

        UserExtension userExtension = userExtensionService.getByUserId(userId);

        // 获取用户可用余额
        Long balance = userExtension.getActualBalance();

        // 需要支付的金额
        UserBalanceLog userBalanceLog = userBalanceLogService.getByPayId(payId);
        if (userBalanceLog.getChangeBalance() > balance) {
            return ServerResponseEntity.showFailMsg("余额不足");
        }

        TransactionSendResult transactionSendResult = balancePayTemplate.sendMessageInTransaction(RocketMqConstant.BALANCE_PAY_TOPIC, new GenericMessage<>(payId), userBalanceLog);

        if (!Objects.equals(transactionSendResult.getLocalTransactionState(), LocalTransactionState.COMMIT_MESSAGE)) {
            throw new LuckException(ResponseEnum.EXCEPTION);
        }
        return ServerResponseEntity.success();
    }



}
